﻿using UnityEngine;
using System.Collections;

public class UseScript : MonoBehaviour {

	float detectRange = 1f;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetButtonDown ("Use")){
			useClosestItem();
		}
	}

	void useClosestItem(){
		Collider[] collide = Physics.OverlapSphere (new Vector3 (transform.position.x, transform.position.y, transform.position.z), detectRange, 1 << LayerMask.NameToLayer ("Usable"));
		if (collide.Length > 0) {
			findClosestItem(collide).GetComponent<BaseUsableObject>().use (gameObject);
		}
	}

	GameObject findClosestItem(Collider[] collide){
		GameObject closest = null;
		float minDist = Mathf.Infinity;
		foreach(Collider col in collide){
			float dist = Vector3.Distance(col.transform.position, transform.position);
			if(dist < minDist){
				minDist = dist;
				closest = col.gameObject;
			}
		}
		return closest;
	}
}
